<?php

namespace app\api\model;

use app\admin\utils\ontimeLog;
use think\Db;


class ProductModel extends Model
{
    //分页查询
    public function list($page, $limit, $param)
    {
        return Db::table('product')
            ->field('pro_no, product_cates.title cate, product.title, keywords, img, price, product.add_time')
            ->where($param)
            ->where('product.status', 1)
            ->join('product_cates', 'product.cid = product_cates.id', 'left')
            ->order('product.add_time', 'desc')
            ->page($page, $limit)->select();
    }

    public function count(): int
    {
        return Db::table('product')->count();
    }

    public function detail($pro_no)
    {
        Db::startTrans();
        try {
            $data = Db::table('product')
                ->field('product.id ,pro_no, product_cates.title cate, product.title, keywords, img, price, pv,product.add_time')
                ->where('product.pro_no', $pro_no)
                ->where('product.status', 1)
                ->join('product_cates', 'product.cid = product_cates.id', 'left')
                ->select();
            $pv = $data[0]['pv'];
//            ontimeLog::mylog($pv, __FILE__, __METHOD__);
            Db::table('product')->where('product.pro_no', $pro_no)->update(['pv' => $pv + 1]);
            Db::commit();
            return $data;
        } catch (\Throwable $e) {
            Db::rollback();
            ontimeLog::mylog("detail事务失败", __FILE__, __METHOD__);
        }
        return [];
    }

    public function search($keyword, $page, $limit)
    {
        $data = Db::table('product')
            ->field('count', 'product.id ,pro_no, product_cates.title cate, product.title, keywords, img, price, product.add_time')
            ->where('title', 'like', '%' . $keyword . '%')
            ->whereOr('keywords', 'like', '%' . $keyword . '%')
            ->order('product.add_time', 'desc')
            ->page($page, $limit)
            ->select();
        $data['count'] = count($data);
        ontimeLog::mylog($keyword, __FILE__, __METHOD__);

        ontimeLog::mylog(Db::table('product')->getLastSql(), __FILE__, __METHOD__);

        return $data;

    }

    public function getSku($product_id)
    {
        $data = Db::table('product_sku')
            ->field('id sku_id, sku_title, sku_price, sku_count')
            ->where('product_id', $product_id)
            ->select();

        return $data;
    }


}